package com.yu.boot2.controller;

import com.yu.boot2.domain.Result;
import com.yu.boot2.exception.ErrorCode;
import com.yu.boot2.oss.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zy
 * @date 2019-05-27 15:11
 **/
@Api(value = "图片管理",tags = "图片管理")
@RestController
@RequestMapping("oss")
public class OssController {

    @Autowired
    private OssService ossService;

    @ApiOperation(value = "获取图片信息接口")
    @GetMapping("/info")
    public Result getInfo(@RequestParam String name){
        Map<String,Object> map = new HashMap<>();
        map.put("data",ossService.getInfo(name));
        return Result.ok(map);
    }

    @ApiOperation(value = "获取图片列表接口")
    @GetMapping("/list")
    public Result getList(){
        Map<String,Object> map = new HashMap<>();
        map.put("data",ossService.getList("renren"));
        return Result.ok(map);
    }

    @ApiOperation(value = "上传文件")
    @ApiImplicitParams(@ApiImplicitParam(name = "file", value = "文件流对象,接收数组格式", required = true, dataType = "__File"))
    @PostMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return Result.error(ErrorCode.UPLOAD_FILE_EMPTY+"");
        }

        //上传文件
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String url = ossService.uploadSuffix(file.getBytes(), extension);

        //保存文件信息


        Map<String, Object> data = new HashMap<>(1);
        data.put("src", url);

        return Result.ok(data);
    }
}
